<?php

namespace App\Http\Middleware;

use Closure;
use GuzzleHttp\ClientInterface;
use Illuminate\Container\Container;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use App\Http\Responses\RespondsJson;

class ConsoleAuthenticate

{
    use RespondsJson;

    /*
     * var ClientInterface $client
     */
    private $client;

    public function __construct(ClientInterface $client)
    {
        $this->client = $client;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     * @throws \Exception
     */
    public function handle(Request $request, Closure $next)
    {
        $config = Container::getInstance()->make('config');
        $loginUrl = $config->get('console.login_url');

        if (!isset($_COOKIE['usertoken'])) {
            return $this->noLoginReturn($request, $loginUrl);
        }

        $userCheckUrl = $config->get('console.check_login_url');

        if (empty($userCheckUrl)) {
            throw new \Exception('user login config error');
        }

        $profile = $this->httpRequest($userCheckUrl);
        //var_dump($profile);exit;

        if (Arr::get($profile, 'code') != 10000) {
            return $this->noLoginReturn($request, $loginUrl);
        }
        $request->session()->put('userid', Arr::get($profile, 'params.usertoken'));
        $request->session()->put('username', Arr::get($profile, 'params.login_name'));
        $request->session()->put('groupcode', Arr::get($profile, 'params.groupcode'));

        return $next($request);
    }

    public function httpRequest($url)
    {
        $url = $url . '?' . http_build_query(['usertoken' => $_COOKIE['usertoken']]);
        $response = $this->client->request('GET', $url);

        if ($response->getStatusCode() != 200) {
            throw new \Exception('bad response from console server: ' . (string)$response->getBody());
        }
        $content = $response->getBody()->getContents();
        if (empty($content)) {
            throw new \Exception('Unauthorized');
        }
        $response = json_decode($content, true);
        if (!is_array($response)) {
            throw new \Exception('bad response from console server: ' . (string)$response->getBody());
        }

        return $response;
    }

    /**
     * 如果没有登录 重定向 / ajax请求返回401状态码
     * @param Request $request
     * @param $loginUrl
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|string
     */
    private function noLoginReturn(Request $request, $loginUrl)
    {
        if ($request->ajax()) {
//            return response(
//                \GuzzleHttp\json_encode(['redirect' => $loginUrl]),
//                401,
//                [
//                    'content-type' => 'application/json',
//                    'accept'       => 'application/json',
//                ]
//            );
        return returnMsgToJson(['redirect'=> $loginUrl],401,'error');
//                        return returnMsg(401,'',['redirect'=>$loginUrl]);

        }
        return redirect($loginUrl);
    }

}
